#include "stdafx.h"
#include "file.h"

CFile::CFile()
{
	m_pFile = NULL;
}

CFile::~CFile()
{
	UnInit();
}

bool CFile::Init(const char* pcszFileName, const char* pcszMode)
{
	LOG_PROCESS_ERROR(pcszFileName);
	LOG_PROCESS_ERROR(pcszMode);
	
	LOG_PROCESS_ERROR(m_pFile == NULL);

	m_pFile = fopen(pcszFileName, pcszMode);
	LOG_PROCESS_ERROR(m_pFile);

	strncpy(m_szFileName, pcszFileName, MAX_FILE_NAME_LEN);

	return true;
Exit0:
	UnInit();

	return false;
}

bool CFile::UnInit(void)
{
	if (m_pFile)
		fclose(m_pFile);
	m_pFile = NULL;

	return true;
}

int CFile::Read(void* pBuffer, size_t uElementSize, size_t uCount)
{
	return fread(pBuffer, uElementSize, uCount, m_pFile);
}

int CFile::Write(void* pBuffer, size_t uElementSize, size_t uCount)
{
	return fwrite(pBuffer, uElementSize, uCount, m_pFile);
}

int CFile::Seek(long lOffset, int nOrigin)
{
	return fseek(m_pFile, lOffset, nOrigin);
}

size_t CFile::Size(void)
{
	size_t uResult = 0;
	int nRetCode = 0;

	long lOffset = ftell(m_pFile);

	nRetCode = fseek(m_pFile, 0, SEEK_END);
	LOG_PROCESS_ERROR(nRetCode == 0);

	uResult = ftell(m_pFile);
Exit0:

	fseek(m_pFile, lOffset, SEEK_SET);

	return uResult;
}

IFile* g_OpenFile(const char* pcszFileName, const char* pcszMode)
{
	int nRetCode = 0;
	CFile* pFile = NULL;

	pFile = new CFile;
	LOG_PROCESS_ERROR(pFile);

	nRetCode = pFile->Init(pcszFileName,pcszMode);
	LOG_PROCESS_ERROR(nRetCode);

	return pFile;
Exit0:
	SAFE_DELETE(pFile);

	return NULL;
}

void g_CloseFile(IFile* pFile)
{
	LOG_PROCESS_ERROR(pFile);

	CFile* pCFile = (CFile*)pFile;
	SAFE_DELETE(pCFile);

Exit0:
	return;
}
